package com.cci.kangdao.service.impl;


import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.MPUrlService;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.ParameterTool;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service("MPUrlService")
public class MPUrlServiceImpl implements MPUrlService {

	private Logger log = Logger.getLogger(this.getClass().getName());
	@Resource
	private RedisClientUtils redisClientUtils;
	@Resource
	private DictionariesTDao dictionariesTDao;

	//获取网上商城url地址
	@Override
	public ModelAndView getUrlByKey(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			String key = MapUtils.getString(map,"key","");
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			if (StringUtils.isEmpty(key)) {
				obj.put("status", 17);
				obj.put("msg", "缺少必要参数");
				obj.put("data", "");
			} else {
				//stg环境redis中这个值保存为空格，字典表保存为空字符串    正式环境redis和字典表中保存为正式环境网上商城地址
				String keyUrl = redisClientUtils.get(key);
				if(null == keyUrl || (null != keyUrl && StringUtils.isEmpty(keyUrl.trim()))){
					List<Map<String,Object>> dictionariesList = dictionariesTDao.getDictionariesListByDTableName(key);
					if(CollectionUtils.isNotEmpty(dictionariesList)){
						keyUrl = MapUtils.getString(dictionariesList.get(0),"DValue","");
					}
				}else{
					keyUrl = keyUrl.trim();
				}
				obj.put("status", 0);
				obj.put("msg", "success");
				Map<String,Object> keyMap = new HashMap<>();
				keyMap.put("url",keyUrl);
				obj.put("data", keyMap);
			}
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);	
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}
	

}
